﻿/*
 * @author: wizardc
 */

using System;
using System.Collections;
using Dou.Audio;
using UnityEngine;
using UnityEngine.Video;

namespace Dou.Video
{
    /// <summary>
    /// 视频控制器
    /// </summary>
    [RequireComponent(typeof(VideoPlayer))]
    public class VideoController : MonoBehaviour
    {
        private VideoPlayer _videoPlayer;
        
        private Action _onDataPrepare;

        private VideoPlayer videoPlayer
        {
            get
            {
                if (_videoPlayer == null)
                {
                    _videoPlayer = GetComponent<VideoPlayer>();
                }

                return _videoPlayer;
            }
        }

        void Awake()
        {
            videoPlayer.prepareCompleted += PrepareCompletedHandler;
        }

        private void PrepareCompletedHandler(VideoPlayer source)
        {
            StartCoroutine(WaitFrame());
        }

        private IEnumerator WaitFrame()
        {
            if (_onDataPrepare != null)
            {
                // 保证有可播放的帧数后再播放避免播放开始出现黑屏情况
                while (videoPlayer.frame < 1)
                {
                    yield return 0;
                }

                // 数据已经准备好了，暂停播放
                videoPlayer.Pause();

                _onDataPrepare();
                _onDataPrepare = null;
            }
        }

        /// <summary>
        /// 加载视频文件
        /// </summary>
        /// <param name="path">视频资源 url 地址</param>
        /// <param name="onDataPrepare">视频资源已经准备好时的回调，请在改回调里调用 Play 方法进行播放</param>
        public void Load(string path, Action onDataPrepare)
        {
            videoPlayer.url = path;
            
            // 打开声音
            videoPlayer.controlledAudioTrackCount = 1;
            // 根据音效设置音量
            videoPlayer.SetDirectAudioVolume(0, AudioManager.instance.GetBGVolume());
            
            if (videoPlayer.isPrepared && videoPlayer.frame > 0)
            {
                onDataPrepare?.Invoke();
            }
            else
            {
                // 需要调用播放后才会有 prepareCompleted 事件
                videoPlayer.Play();
                _onDataPrepare = onDataPrepare;
            }
        }
        
        /// <summary>
        /// 播放视频
        /// </summary>
        public void Play()
        {
            videoPlayer.Play();
        }
    }
}
